package com.fooddiary.web;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.fooddiary.service.IModelService;
import com.fooddiary.service.IWeightService;
import com.fooddiary.util.AppException;
import com.fooddiary.util.SortPaginationBean;
import com.fooddiary.web.form.WeightForm;

/**
 * Dispathc requests for model CRUD functionality <br>
 * @author Created by andrey.kuznetsov <br>
 * @author Last modified by $Author$ <br>
 * @author Last modified on $Date$ at revision $Revision$ <br>
 */
@Controller
@RequestMapping(value="/private/model*")
public class ModelController extends AbstractController{

	private final String MAIN_URL = "/private/main";
	private final String PRINT_URL = "/private/print";
	
	@Autowired
	IModelService modelService;
	
	@Autowired
	IWeightService weightService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="main.action")
	public ModelAndView loadMainPage(
			@RequestParam (value = "dir", required = false ) String dir,
			@RequestParam (value = "limit", required = false ) Integer limit,
			@RequestParam (value = "sort", required = false ) String sort,
			@RequestParam (value = "start", required = false ) Integer start,
			@RequestParam (value = "print", required = false ) Boolean print){
		try{
			ModelAndView mv = ( print != null && print ) ? 
					new ModelAndView( PRINT_URL ) : new ModelAndView( MAIN_URL );
			Object[] data = weightService.loadRecords( modelService.getModel(), new SortPaginationBean( sort, dir, start, limit ) );
			List<WeightForm> weightFormList = (List<WeightForm>) data[0];
			Long totalCount = (Long) data[1];
			mv.addObject( "weights", weightFormList );
			mv.addObject( "totalCount", totalCount );
			return mv;
		} catch (AppException error) {
			return new ModelAndView(ERROR_URL);
		} 
	}
}
